extends Node

## 游戏保存管理器
## 负责管理游戏的自动保存功能，包括战斗后保存和定时自动保存

# 自动保存配置
var auto_save_interval: float = 60.0  # 自动保存间隔（秒）
var last_save_time: float = 0.0  # 上次保存时间
var current_save_slot: int = -1  # 当前使用的存档槽
var is_auto_save_enabled: bool = true  # 是否启用自动保存

# 保存数据结构
var save_data: Dictionary = {}

# 定时器
var auto_save_timer: Timer

func _ready():
	# 设置为自动加载单例
	process_mode = Node.PROCESS_MODE_ALWAYS
	
	# 创建自动保存定时器
	auto_save_timer = Timer.new()
	auto_save_timer.wait_time = auto_save_interval
	auto_save_timer.timeout.connect(_on_auto_save_timer_timeout)
	auto_save_timer.autostart = false
	add_child(auto_save_timer)
	
	# 连接战斗结束信号
	if BattleManager != null:
		BattleManager.battle_ended.connect(_on_battle_ended)
	
	# 禁用自动退出，以便我们可以在退出前保存游戏
	get_tree().set_auto_accept_quit(false)
	
	# 加载现有存档数据
	_load_save_data()
	
	print("游戏保存管理器初始化完成")

func _on_battle_ended(victory: bool):
	"""战斗结束后处理（自动保存已移至场景切换完成后）"""
	if victory:
		print("战斗胜利，等待场景切换完成后自动保存...")
	else:
		print("战斗失败，不进行自动保存")
		# 重置自动保存计时器
		reset_auto_save_timer()

func _notification(what):
	"""处理系统通知"""
	if what == NOTIFICATION_WM_CLOSE_REQUEST:
		print("检测到窗口关闭请求，正在自动保存游戏...")
		
		# 如果有活跃的存档槽，进行自动保存
		if current_save_slot >= 0:
			var save_success = save_game_to_slot(current_save_slot)
			if save_success:
				print("退出前自动保存成功")
			else:
				print("退出前自动保存失败")
		else:
			print("没有活跃的存档槽，跳过自动保存")
		
		# 允许游戏退出
		get_tree().quit()

func _on_auto_save_timer_timeout():
	"""定时自动保存"""
	if is_auto_save_enabled and current_save_slot >= 0:
		print("定时自动保存游戏...")
		save_game_to_slot(current_save_slot)

func set_current_save_slot(slot_index: int):
	"""设置当前使用的存档槽"""
	current_save_slot = slot_index
	print("设置当前存档槽: ", slot_index + 1)
	
	# 启动自动保存计时器
	if is_auto_save_enabled:
		start_auto_save_timer()

func load_game_data(slot_index: int):
	"""加载游戏数据（兼容性函数）"""
	# 这个函数主要用于兼容主菜单的调用
	# 实际的数据加载由各个管理器负责
	print("GameSaveManager: 加载存档槽 ", slot_index + 1, " 的数据")
	# 可以在这里添加额外的加载逻辑，如果需要的话

func start_auto_save_timer():
	"""启动自动保存计时器"""
	if auto_save_timer != null:
		auto_save_timer.start()
		print("自动保存计时器已启动，间隔: ", auto_save_interval, "秒")

func stop_auto_save_timer():
	"""停止自动保存计时器"""
	if auto_save_timer != null:
		auto_save_timer.stop()
		print("自动保存计时器已停止")

func reset_auto_save_timer():
	"""重置自动保存计时器"""
	if auto_save_timer != null and is_auto_save_enabled:
		auto_save_timer.stop()
		auto_save_timer.start()
		print("自动保存计时器已重置")

func save_game_to_slot(slot_index: int) -> bool:
	"""保存游戏到指定存档槽"""
	var slot_key = "slot_" + str(slot_index)
	var current_time = Time.get_datetime_string_from_system()
	
	# 收集游戏数据
	var game_data = _collect_game_data()
	if game_data.is_empty():
		print("错误：无法收集游戏数据")
		return false
	
	# 创建存档数据
	var slot_data = {
		"level": game_data.get("level", 1),
		"play_time": _calculate_play_time(),
		"save_time": current_time,
		"scene": _get_current_scene_path(),
		"player_position": _get_player_position(),
		"player_stats": game_data.get("player_stats", {}),
		"phantom_beasts": game_data.get("phantom_beasts", {}),
		"inventory": game_data.get("inventory", {}),
		"equipment": game_data.get("equipment", {})
	}
	
	save_data[slot_key] = slot_data
	
	# 保存到文件
	var save_file_path = "user://save_data.json"
	var file = FileAccess.open(save_file_path, FileAccess.WRITE)
	if file != null:
		var json_string = JSON.stringify(save_data)
		file.store_string(json_string)
		file.close()
		print("游戏数据已保存到存档槽 ", slot_index + 1)
		last_save_time = Time.get_time_dict_from_system().hour * 3600 + Time.get_time_dict_from_system().minute * 60 + Time.get_time_dict_from_system().second
		return true
	else:
		print("保存失败：无法创建存档文件")
		return false

func _collect_game_data() -> Dictionary:
	"""收集当前游戏数据"""
	var game_data = {}
	
	# 收集玩家属性数据
	if PlayerStatsManager != null:
		game_data["player_stats"] = PlayerStatsManager.save_stats_data()
		game_data["level"] = PlayerStatsManager.get_level()
	
	# 收集幻兽数据
	if PhantomBeastManager != null:
		game_data["phantom_beasts"] = {
			"owned_phantom_beasts": PhantomBeastManager.owned_phantom_beasts,
			"active_formation": PhantomBeastManager.active_formation,
			"next_beast_id": PhantomBeastManager.next_beast_id
		}
	
	# 收集背包和装备数据
	if ItemManager != null:
		game_data["inventory"] = _get_inventory_data()
		game_data["equipment"] = _get_equipment_data()
	
	return game_data

func _get_inventory_data() -> Dictionary:
	"""获取背包数据"""
	var inventory_data = {
		"consumables": [],
		"materials": [],
		"equipment": []
	}
	
	if ItemManager != null:
		# 获取消耗品背包数据
		for i in range(ItemManager.INVENTORY_SIZE):
			var slot = ItemManager.inventory_consumable[i]
			if not slot.is_empty():
				inventory_data["consumables"].append({
					"index": i,
					"item_id": slot.item_data.id,
					"quantity": slot.quantity
				})
		
		# 获取材料背包数据
		for i in range(ItemManager.INVENTORY_SIZE):
			var slot = ItemManager.inventory_material[i]
			if not slot.is_empty():
				inventory_data["materials"].append({
					"index": i,
					"item_id": slot.item_data.id,
					"quantity": slot.quantity
				})
		
		# 获取装备背包数据
		for i in range(ItemManager.INVENTORY_SIZE):
			var slot = ItemManager.inventory_equipment[i]
			if not slot.is_empty():
				var equipment_info = {
					"index": i,
					"item_id": slot.item_data.id,
					"quantity": slot.quantity
				}
				# 如果是装备，保存强化等级
				if slot.item_data is ItemManager.EquipmentData:
					var equipment = slot.item_data as ItemManager.EquipmentData
					equipment_info["enhancement_level"] = equipment.enhancement_level
				inventory_data["equipment"].append(equipment_info)
	
	return inventory_data

func _get_equipment_data() -> Dictionary:
	"""获取装备数据"""
	var equipment_data = {}
	
	if ItemManager != null:
		for slot_type in ItemManager.equipment_slots.keys():
			var equipment = ItemManager.equipment_slots[slot_type]
			if equipment != null:
				equipment_data[str(slot_type)] = {
					"id": equipment.id,
					"enhancement_level": equipment.enhancement_level
				}
	
	return equipment_data

func _get_current_scene_path() -> String:
	"""获取当前场景路径"""
	var current_scene = get_tree().current_scene
	if current_scene != null:
		return current_scene.scene_file_path
	return "res://scene/scene1.tscn"

func _get_player_position() -> Dictionary:
	"""获取玩家位置"""
	if PlayerManager != null:
		# 优先使用当前玩家位置
		if PlayerManager.has_player():
			var pos = PlayerManager.get_player_position()
			return {"x": pos.x, "y": pos.y}
		# 如果没有玩家实例，使用保存的位置数据
		elif PlayerManager.player_data.has("position"):
			var pos = PlayerManager.player_data["position"]
			if pos != Vector2.ZERO:
				return {"x": pos.x, "y": pos.y}
		# 最后使用默认生成位置
		var default_pos = PlayerManager.default_spawn_position
		return {"x": default_pos.x, "y": default_pos.y}
	# 如果PlayerManager不存在，返回场景1的默认位置
	return {"x": 1088, "y": 514}

func _calculate_play_time() -> String:
	"""计算游戏时间（简化版本）"""
	# 这里可以实现更复杂的游戏时间计算
	# 目前返回简单的格式
	var current_time = Time.get_time_dict_from_system()
	return "%02d:%02d:%02d" % [current_time.hour, current_time.minute, current_time.second]

func _load_save_data():
	"""加载存档数据"""
	var save_file_path = "user://save_data.json"
	if not FileAccess.file_exists(save_file_path):
		print("存档文件不存在，使用空数据")
		return
	
	var file = FileAccess.open(save_file_path, FileAccess.READ)
	if file == null:
		print("错误：无法读取存档文件")
		return
	
	var json_string = file.get_as_text()
	file.close()
	
	var json = JSON.new()
	var parse_result = json.parse(json_string)
	if parse_result != OK:
		print("错误：解析存档文件失败")
		return
	
	save_data = json.data
	print("存档数据加载完成")

func load_game_from_slot(slot_index: int) -> bool:
	"""从指定存档槽加载游戏"""
	var slot_key = "slot_" + str(slot_index)
	
	if not save_data.has(slot_key) or save_data[slot_key] == null:
		print("存档槽 ", slot_index + 1, " 为空")
		return false
	
	var slot_data = save_data[slot_key]
	
	# 标记不是首次生成，避免添加初始装备
	if PlayerManager != null:
		PlayerManager.player_data["is_first_spawn"] = false
	
	# 先恢复背包和装备数据
	if ItemManager != null:
		if slot_data.has("inventory"):
			_restore_inventory_data(slot_data["inventory"])
		if slot_data.has("equipment"):
			_restore_equipment_data(slot_data["equipment"])
	
	# 再恢复玩家属性数据（这样装备加成计算时装备已经正确加载）
	if PlayerStatsManager != null and slot_data.has("player_stats"):
		PlayerStatsManager.load_stats_data(slot_data["player_stats"])
	
	# 恢复幻兽数据
	if PhantomBeastManager != null and slot_data.has("phantom_beasts"):
		var beast_data = slot_data["phantom_beasts"]
		PhantomBeastManager.owned_phantom_beasts = beast_data.get("owned_phantom_beasts", {})
		
		# 正确处理Array[String]类型的active_formation
		var formation_data = beast_data.get("active_formation", [])
		PhantomBeastManager.active_formation.clear()
		for formation_id in formation_data:
			PhantomBeastManager.active_formation.append(str(formation_id))
		
		PhantomBeastManager.next_beast_id = beast_data.get("next_beast_id", 1)
	
	# 设置当前存档槽
	set_current_save_slot(slot_index)
	
	# 设置玩家位置
	if PlayerManager != null and slot_data.has("player_position"):
		var player_pos = slot_data["player_position"]
		# 同时设置默认生成位置和player_data中的位置
		PlayerManager.set_default_spawn_position(Vector2(player_pos.x, player_pos.y))
		PlayerManager.player_data["position"] = Vector2(player_pos.x, player_pos.y)
	
	print("从存档槽 ", slot_index + 1, " 加载游戏完成")
	return true

func _restore_inventory_data(inventory_data: Dictionary):
	"""恢复背包数据"""
	if ItemManager == null:
		return
	
	# 清空当前背包
	ItemManager.clear_all_inventories()
	
	# 恢复消耗品
	if inventory_data.has("consumables"):
		for item_info in inventory_data["consumables"]:
			var consumable = ItemManager.get_consumable_by_id(item_info["item_id"])
			if consumable != null:
				ItemManager.add_consumable_to_inventory(consumable, item_info["quantity"])
	
	# 恢复材料
	if inventory_data.has("materials"):
		for item_info in inventory_data["materials"]:
			var material = ItemManager.get_material_by_id(item_info["item_id"])
			if material != null:
				ItemManager.add_material_to_inventory(material, item_info["quantity"])
	
	# 恢复装备
	if inventory_data.has("equipment"):
		for item_info in inventory_data["equipment"]:
			# 为每个装备数量创建独立的副本
			var quantity = item_info["quantity"]
			for i in range(quantity):
				var equipment = ItemManager.get_equipment_by_id(item_info["item_id"])
				if equipment != null:
					# 恢复强化等级
					if item_info.has("enhancement_level"):
						equipment.enhancement_level = item_info["enhancement_level"]
					ItemManager.add_equipment_to_inventory(equipment, 1)

func _restore_equipment_data(equipment_data: Dictionary):
	"""恢复装备数据"""
	if ItemManager == null:
		return
	
	# 设置加载标记，防止装备恢复过程中触发属性更新
	PlayerStatsManager._is_loading_save_data = true
	
	# 清空当前装备
	ItemManager.unequip_all()
	
	# 恢复装备
	for slot_type_str in equipment_data.keys():
		var equipment_info = equipment_data[slot_type_str]
		var equipment_id: String
		var enhancement_level: int = 0
		
		# 兼容旧版本存档格式
		if equipment_info is String:
			equipment_id = equipment_info
		elif equipment_info is Dictionary:
			equipment_id = equipment_info.get("id", "")
			enhancement_level = equipment_info.get("enhancement_level", 0)
		
		var equipment = ItemManager.get_equipment_by_id(equipment_id)
		if equipment != null:
			# 恢复强化等级
			equipment.enhancement_level = enhancement_level
			var slot_type = int(slot_type_str)
			ItemManager.equipment_slots[slot_type] = equipment
			# 为每个装备槽位发射装备变化信号
			ItemManager.equipment_changed.emit(slot_type, equipment)
	
	# 清除加载标记
	PlayerStatsManager._is_loading_save_data = false
	
	# 装备恢复完成后，确保PlayerStatsManager更新装备加成
	# 注意：不在这里调用update_equipment_bonus，因为它会在load_stats_data中统一处理

func set_auto_save_enabled(enabled: bool):
	"""设置是否启用自动保存"""
	is_auto_save_enabled = enabled
	if enabled and current_save_slot >= 0:
		start_auto_save_timer()
	else:
		stop_auto_save_timer()
	print("自动保存功能: ", "启用" if enabled else "禁用")

func set_auto_save_interval(interval: float):
	"""设置自动保存间隔"""
	auto_save_interval = max(10.0, interval)  # 最小10秒
	if auto_save_timer != null:
		auto_save_timer.wait_time = auto_save_interval
	print("自动保存间隔设置为: ", auto_save_interval, "秒")

func get_save_slot_info(slot_index: int) -> Dictionary:
	"""获取存档槽信息"""
	var slot_key = "slot_" + str(slot_index)
	if save_data.has(slot_key) and save_data[slot_key] != null:
		return save_data[slot_key]
	return {}

func manual_save():
	"""手动保存游戏"""
	if current_save_slot >= 0:
		print("手动保存游戏...")
		save_game_to_slot(current_save_slot)
		reset_auto_save_timer()
	else:
		print("错误：没有设置当前存档槽")
